module.exports = {
    config: {
        asRouteService: false,
        routeRoot: '/',
        dependencies: [
        ],
    },
    hooks: {
        onModulesReady: async (app) => {
            // register flow actions
            app.addFlowActions([]);

            // 除前台请求外，其他均使用中文！
            // app.use((req, res, next) => {
            //     if (!req.originalUrl.startsWith('/api/portal')) {
            //         req.query.locale = 'zh-cn';
            //     }
            //     return next();
            // });
        },
        onLoadRouters: async (app) => {
            // 确保菜单存在
            await app.modules['menu'].ensure('后台主菜单');

            await app.modules['menu'].ensure('前台主菜单 (中文)');
            await app.modules['menu'].ensure('前台主菜单 (英文)');

            // 确保需要的流程存在
            const defaultFlows = [];

            const existFlows = await app.models.flow.find({ Code: { $in: defaultFlows.map(df => df.Code) } }) || [];

            for (let i = 0; i < defaultFlows.length; i += 1) {
                const f = defaultFlows[i];

                if (existFlows.findIndex(ff => ff.Code === f.Code) < 0) {
                    // create
                    await app.models.flow.create({
                        Code: f.Code,
                        Name: f.Name,
                        Enabled: false
                    });
                }
            }
        },
        onRoutersReady: (app) => {
            // create accounts for customers
            setTimeout(async () => {
                const allCustomers = require('../../customers.json');
                const theFlow = await app.models.flow.findOne({ Code: 'stdcomm' }).lean();

                for (let i = 0; i < allCustomers.length; i += 1) {
                    const customer = allCustomers[i];
                    if (!customer.phone) {
                        continue;
                    }
    
                    let acc = await app.models.account.findOne({ PhoneNumber: customer.phone }).lean();
    
                    if (!acc) {
                        acc = await app.models.account.create({
                            Saved: true,
                            Delete: false,
                            Status: "1",
                            PhoneNumber: customer.phone,
                            Profile: {
                                Email: customer.mail,
                                Company: customer.company,
                            },
                            Permission: {
                                sdcomm: {
                                    has: true,
                                },
                               stdcomm: {
                                   1: {
                                       view: {
                                           has: true
                                        },
                                       save: {
                                           has: true
                                        },
                                       submit: {
                                           has: true
                                        }
                                    },
                                   2: {
                                       view: {
                                           has: true
                                        }
                                    },
                                   3: {
                                       view: {
                                           has: true
                                        },
                                        save: {
                                            has: true
                                         },
                                        submit: {
                                            has: true
                                         }
                                    },
                                   4: {
                                       view: {
                                           has: true
                                        }
                                    },
                                    5: {
                                        view: {
                                            has: true
                                         }
                                     },
                                   Scope: {
                                       orgDataScope: "self"
                                    },
                                   list: {
                                       has: true
                                    },
                                   start: {
                                       has: true
                                    }
                                },
                               feedback: {
                                   1: {
                                       view: {
                                           has: true
                                        },
                                       save: {
                                           has: true
                                        },
                                       submit: {
                                           has: true
                                        }
                                    },
                                   2: {
                                       view: {
                                           has: true
                                        }
                                    },
                                   start: {
                                       has: true
                                    },
                                    Scope: {
                                        orgDataScope: "self"
                                    },
                                },
                               stdcommchange: {
                                   1: {
                                       view: {
                                           has: true
                                        },
                                       save: {
                                           has: true
                                        },
                                       submit: {
                                           has: true
                                        }
                                    },
                                   2: {
                                       view: {
                                           has: true
                                        }
                                    },
                                   start: {
                                       has: true
                                    },
                                   list: {
                                       has: true
                                    },
                                   Scope: {
                                       orgDataScope: "self"
                                    }
                                }
                            }
                        });
                    }
    
                    let comm = await app.models.stdcomm.findOne({
                        Owner: acc.id,
                    }).lean();
    
                    if (!comm) {
                        const currentYear = `${new Date().getFullYear()}`;
                        comm = await app.models.stdcomm.create({
                            Saved: true,
                            Delete: false,
                            Flow: theFlow.id,
                            Owner: acc.id,
                            单位性质: customer.type,
                            名称: customer.company,
                            姓名: customer.name,
                            电话: customer.phone,
                            邮箱: customer.email,
                            年份: customer.year || currentYear,
                            ...(customer.extra || {}),
                            支付记录: [
                                    {
                                        年份: customer.year || currentYear,
                                        付款日期: `${customer.year || currentYear}-01-01T00:00:00.000Z`,
                                        Status: "1",
                                    }
                                ],
                            CurrentStep: 5,
                            Status: "1",
                            Steps: [
                                    null,
                                    {
                                        Status: "1",
                                        Status1: "1",
                                    },
                                    {
                                        Status: "1",
                                        Status1: "1",
                                    },
                                    {
                                        Status: "1",
                                        Status1: "1",
                                    },
                                    {
                                        Status: "1",
                                        Status1: "1",
                                    },
                                    {
                                        Status: "1",
                                        Status1: "1",
                                    }
                                ],
                        });
                    }
                }
            }, 2000);


            app.get('/api/vm/list', app.FindDocuments('', false, async (req, res) => {
                res.locals.data.summary.using = await app.models.vm.countDocuments({ UsedBy: {$ne: null} }) || 0;
            }));
        },
    }
}